package com.yaozheng.vocationaltraining.activity;

import java.text.SimpleDateFormat;
import java.util.Date;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.Background;
import org.androidannotations.annotations.Bean;
import org.androidannotations.annotations.Click;
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.Extra;
import org.androidannotations.annotations.UiThread;
import org.androidannotations.annotations.ViewById;

import android.support.v4.view.ViewPager;
import android.widget.TextView;

import com.yaozheng.vocationaltraining.R;
import com.yaozheng.vocationaltraining.adapter.PaperQuestionListAdapter;
import com.yaozheng.vocationaltraining.db.PaperAnswerCacheDao;
import com.yaozheng.vocationaltraining.dialog.QuestionNumberListDialog;
import com.yaozheng.vocationaltraining.dialog.paper.CarryOutAnAssignmentAskDialog;
import com.yaozheng.vocationaltraining.dialog.paper.ExamHelpPopupWindow;
import com.yaozheng.vocationaltraining.fragment.ItemQuestionFragment;
import com.yaozheng.vocationaltraining.fragment.PaperQuestionListFragment;
import com.yaozheng.vocationaltraining.fragment.PaperQuestionListFragment_;
import com.yaozheng.vocationaltraining.iview.IOnlineExamView;
import com.yaozheng.vocationaltraining.iview.IQuestionNumberView;
import com.yaozheng.vocationaltraining.iview.exam.IExamHelpView;
import com.yaozheng.vocationaltraining.service.OnlineExamService;
import com.yaozheng.vocationaltraining.service.exam.ExamHelpService;
import com.yaozheng.vocationaltraining.service.impl.OnlineCheckpointsExamServiceImpl_;
import com.yaozheng.vocationaltraining.service.impl.OnlineQuizExamServiceImpl;
import com.yaozheng.vocationaltraining.service.impl.OnlineQuizExamServiceImpl_;
import com.yaozheng.vocationaltraining.service.impl.OnlineQuizzesExamServiceImpl_;
import com.yaozheng.vocationaltraining.service.impl.checkpoints_trip.CheckpointsTripSubmitAnswersServiceImpl;
import com.yaozheng.vocationaltraining.service.impl.checkpoints_trip.CheckpointsTripSubmitAnswersServiceImpl_;
import com.yaozheng.vocationaltraining.service.impl.exam.ExamHelpServiceImpl;
import com.yaozheng.vocationaltraining.service.impl.limited.TimedAnswerServiceImpl_;
import com.yaozheng.vocationaltraining.utils.Constants;
import com.yaozheng.vocationaltraining.utils.DateUtils;
import com.yaozheng.vocationaltraining.utils.ErrorUtils;
import com.yaozheng.vocationaltraining.utils.JsonUtils;
import com.yaozheng.vocationaltraining.utils.LogUtils;
import com.yaozheng.vocationaltraining.utils.QuestionUtils;
import com.yaozheng.vocationaltraining.utils.StringUtils;
import com.yaozheng.vocationaltraining.utils.TypeUtils;
import com.yaozheng.vocationaltraining.view.QuestionNumberItemView;

/**
 * 在线考试
 *
 * @author Administrator
 */
@EActivity(R.layout.activity_online_exam)
public class OnlineExamActivity extends BaseActivity implements
        IOnlineExamView, ViewPager.OnPageChangeListener, IQuestionNumberView, IExamHelpView {
    // /**
    // * 试卷题目列表
    // */
    // PaperQuestionListFragment paperQuestionListFragment;
    @ViewById
    TextView examQuestionCountTextView, examTimeTextView, examHelpTextView,

    examCarryOutAnAssignmentText;
    @ViewById
    ViewPager viewPager;
    @ViewById
    TextView headTitleText;
    /**
     * 题目号码对话框
     */
    QuestionNumberListDialog questionNumberListDialog;

    OnlineExamService onlineExamService;

    JSONObject paperJsonObject;
    JSONArray questionJsonArray;

    PaperQuestionListAdapter paperQuestionListAdapter;


    int currPosition;

    SimpleDateFormat simpleDateFormat;
    /**
     * 开始时间
     */
    Date startTimeDate;
    /**
     * 结束时间
     */
    long endTime;
    /**
     * 开始时间
     */
    long startTime;
    /**
     * 交卷时间
     */
    long carryOutAnAssignmentTime;
    /**
     * 本地答案
     */
    String localAnswersContent;

    PaperAnswerCacheDao paperAnswerCacheDao;
    /**
     * 是否交卷
     */
    boolean isCarryOutAnAssignment;

    /**
     * 1:每日一测  2:随堂考试 4:大师之路 5:极限挑战  6:闯关练习
     * // 6+1 形象大师 7
     * // 6+2 维保大师 8
     * // 6+3 服务大师 9
     * // 6+4 销售大师 10
     * // 6+5 商品大师 11
     * // 6+6 品牌大师 12
     */
    @Extra
    String examType;

    int examTypeInt;
    /**
     * 上页面传过来的题目
     */
    @Extra
    String questionJsonObject;
    @Extra
    int paperId;
    @Extra
    String examTitle;

    @Bean(ExamHelpServiceImpl.class)
    ExamHelpService examHelpService;

    CarryOutAnAssignmentAskDialog carryOutAnAssignmentAskDialog;
    ExamHelpPopupWindow examHelpPopupWindow;
    /**
     * 延时卡(1)和提示卡(2)。
     */
    int itemId;
    /**
     * 提示卡可用次数
     */
    int alertCardAvailableCount = 3;
    /**
     * 加时卡
     */
    int overtimeCardCount = 3;

    @AfterViews
    public void initView() {
        headTitleText.setText(examTitle);
//        if (isCarryOutAnAssignment) {
//            getBaseActivity().backClick();
//        }
        System.out.println("---paperId=" + paperId);
        System.out.println("---examType=" + examType);
        System.out.println("---questionJsonObject=" + questionJsonObject);
        examHelpService.init(this);
        paperAnswerCacheDao = new PaperAnswerCacheDao(this);
        try {
            examTypeInt = Integer.parseInt(examType);
        } catch (Exception ex) {
            examTypeInt = -1;
            examType = "-1";
        }
        if ("1".equals(examType)) {
            // 每日一测
            onlineExamService = OnlineQuizzesExamServiceImpl_
                    .getInstance_(this);
        } else if ("2".equals(examType) || "3".equals(examType)) {
            // 随堂考试
            onlineExamService = OnlineQuizExamServiceImpl_.getInstance_(this);
        } else if ("7".equals(examType)
                || "8".equals(examType)
                || "9".equals(examType)
                || "10".equals(examType)
                || "11".equals(examType)
                || "12".equals(examType)
                ) {

            // 6+1 形象大师 7
            // 6+2 维保大师 8
            // 6+3 服务大师 9
            // 6+4 销售大师 10
            // 6+5 商品大师 11
            // 6+6 品牌大师 12
            // 大师之路
            onlineExamService = OnlineCheckpointsExamServiceImpl_
                    .getInstance_(this);
            startTimeDate = new Date(getIntentLong("startTimeLong",
                    System.currentTimeMillis()));
            paperJsonObject = JsonUtils
                    .getJsonObject(getIntentString("paperJsonObjectStr"));
            if (paperJsonObject == null) {
                alertMessage("参数错误,无法考试");
                backClick();
                return;
            }

        } else if ("5".equals(examType)) {
            //极限挑战  每次进来试卷都不一样 所以要每次出来删除数据
            onlineExamService = TimedAnswerServiceImpl_
                    .getInstance_(this);

        } else if ("6".equals(examType)) {
            // 闯关练习
            onlineExamService = CheckpointsTripSubmitAnswersServiceImpl_
                    .getInstance_(this);
            startTimeDate = new Date(getIntentLong("startTimeLong",
                    System.currentTimeMillis()));
            paperJsonObject = JsonUtils
                    .getJsonObject(getIntentString("paperJsonObjectStr"));
            if (paperJsonObject == null) {
                alertMessage("参数错误,无法考试");
                backClick();
                return;
            }

        } else {
            alertMessage("参数错误,无法考试");
            backClick();
            return;
        }
//		examCarryOutAnAssignmentText.setSelected(true);
        // paperQuestionListFragment = PaperQuestionListFragment_.builder()
        // .build();
        // showCurrFragment(paperQuestionListFragment, false);
        onlineExamService.init(this);

        simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        if (startTimeDate == null) {
            String startTimeStr = getIntentString("startTime");
            if (startTimeStr == null || "".equals(startTimeStr)) {
            } else {
                try {
                    startTimeDate = simpleDateFormat.parse(startTimeStr);
                } catch (Exception e) {
                    startTimeDate = new Date();
                    ErrorUtils.outErrorLog(e);
                }

            }
        }
        startTimeDate = new Date();
        startTime = startTimeDate.getTime();


        isCarryOutAnAssignment = false;
        viewPager.setOnPageChangeListener(this);
        loadData();
    }

    /**
     * 加载数据
     */
    public void loadData() {
        try {
//            localAnswersContent = paperAnswerCacheDao.get(String
//                    .valueOf(paperId));
            localAnswersContent = null;
            JSONObject returnJsonObject = paperAnswerCacheDao.getPaperQuestionJsonObject(String
                    .valueOf(paperId));
            if (returnJsonObject != null) {
                paperJsonObject = TypeUtils.getJsonObject(returnJsonObject, "paperQuestions");
                endTime = TypeUtils.getJsonLong(returnJsonObject, "endTime");
                startTime = endTime - (TypeUtils.getJsonInteger(paperJsonObject, "duration", 0) * 1000);
            }

        } catch (Exception e) {
            ErrorUtils.outErrorLog(e);
        }
        if (localAnswersContent != null && !"".equals(localAnswersContent)) {
            JSONObject paperJsonObject = JsonUtils
                    .getJsonObject(localAnswersContent);
            if (paperJsonObject != null) {
                this.paperJsonObject = paperJsonObject;
            }
        }
        if (paperJsonObject == null) {
            if (questionJsonObject != null) {
                paperJsonObject = JsonUtils.getJsonObject(questionJsonObject);
            }
        }
        if (paperJsonObject == null) {

            onlineExamService.getQuestionList(paperId);
        } else {
            refreshData();
        }
    }

    /**
     * 加载更多点击(弹出题号对话框)
     */
    @Click(R.id.footerLoadMoreQuestioinLayout)
    public void loadMoreQuestioinClick() {
        if (questionNumberListDialog == null) {
            questionNumberListDialog = new QuestionNumberListDialog(this);

        }
        questionNumberListDialog.show();
        questionNumberListDialogRefreshData();
    }

    /**
     * 刷新对话框
     */
    public void questionNumberListDialogRefreshData() {
        if (questionNumberListDialog != null
                && questionNumberListDialog.isShowing()) {
            int answeredCount = 0;
            for (int i = 0; i < TypeUtils.getJsonArraySize(questionJsonArray); i++) {
                JSONObject questionJsonObject = TypeUtils.getJsonObject(
                        questionJsonArray, i);
                int questionStatus = TypeUtils.getJsonInteger(
                        questionJsonObject, "questionStatus", 0);
                if (questionStatus == 1) {
                    answeredCount++;
                }
            }
            questionNumberListDialog.refreshData(this, answeredCount);
        }
    }

    /**
     * 下一题
     */
    @Click(R.id.examNextView)
    public void nextQuestion() {

        if (this.currPosition == paperQuestionListAdapter.getCount() - 1) {
            System.out.println("---当前没有下一题！");
            alertMessage("当前没有下一题！");
        } else {
            System.out.println("---nextQuestion=" + currPosition);
            viewPager.setCurrentItem(this.currPosition + 1);
        }
    }

    /**
     * 交卷点击
     */
    @Click(R.id.examCarryOutAnAssignmentText)
    public void examCarryOutAnAssignmentClick() {
        // alertMessage("交卷");
//        examCarryOutAnAssignment();

        showConfirmCancelAskDialog("是否交卷？", null, "examCarryOutAnAssignment");
    }


    /**
     * 交卷
     */
    public void examCarryOutAnAssignment() {
        if (!isCarryOutAnAssignment && isResponseResult()) {
            // questionJsonArray
            isCarryOutAnAssignment = true;
            String answers = QuestionUtils.getAnswers(questionJsonArray);
            LogUtils.println("answers=" + answers);
            showOperatingProgressDialog("交卷中...");
            carryOutAnAssignmentTime = System.currentTimeMillis();
            if (carryOutAnAssignmentTime >= endTime) {
                carryOutAnAssignmentTime = endTime;
            }
            onlineExamService.submitAnswers(
                    paperId,
                    answers == null ? "" : answers);
        }
    }


    @UiThread
    @Override
    public void responseSuccess(JSONObject jsonObject) {
        cancelLoadDataProgressDialog();
        paperJsonObject = TypeUtils.getJsonObject(jsonObject, "data", "paper");
        refreshData();
    }


    /**
     * 刷新数据
     */
    public void refreshData() {
        endTime = startTime
                + (TypeUtils.getJsonInteger(paperJsonObject, "duration", 0) * 1000);

        alertCardAvailableCount = TypeUtils.getJsonInteger(paperJsonObject, "alertCardAvailableCount", 3);
        overtimeCardCount = TypeUtils.getJsonInteger(paperJsonObject, "overtimeCardCount", 3);

        questionJsonArray = TypeUtils
                .getJsonArray(paperJsonObject, "questions");
        if (questionNumberListDialog != null
                && questionNumberListDialog.isShowing()) {
            questionNumberListDialog.refreshData(this, 0);
        }
        System.out.println("---paperQuestionListAdapter=" + paperQuestionListAdapter);
        System.out.println("---questionJsonArray=" + questionJsonArray);
        if (paperQuestionListAdapter == null) {
            paperQuestionListAdapter = new PaperQuestionListAdapter(
                    getSupportFragmentManager(), questionJsonArray);
            viewPager.setAdapter(paperQuestionListAdapter);
        }


//        viewPager
//                .setCurrentItem(TypeUtils.getJsonArraySize(questionJsonArray) * 50);
        viewPager
                .setCurrentItem(0);
        examQuestionCountTextView.setText("1/"
                + TypeUtils.getJsonArraySize(questionJsonArray));
        updateTimingUI();
    }

    /**
     * 考试帮助点击
     */
    @Click(R.id.examHelpTextView)
    public void examHelpClick() {
        if (examHelpPopupWindow == null) {
            examHelpPopupWindow = new ExamHelpPopupWindow(this);
        }
        examHelpPopupWindow.show(examHelpTextView);
    }

    /**
     * 提示卡点击
     */
    public void examAlertClick() {
        /**
         * 提示卡(2)。
         */
        if (alertCardAvailableCount <= 0) {
            alertMessage("一次考试只支持3次提示卡");
        } else {

            if (questionJsonArray != null) {

                JSONObject questionJsonObject = TypeUtils.getJsonObject(questionJsonArray, currPosition);
                JSONArray optionsCard = TypeUtils.getJsonArray(questionJsonObject, "optionsCard");
                if (optionsCard == null) {
                    this.itemId = 2;
                    boolean multiple = TypeUtils.getJsonBoolean(questionJsonObject, "multiple", true);
                    if (multiple) {
                        //多选
                        showConfirmCancelAskDialog("你将消耗10积分，提示一个正确答案，本次考试您还可以使用" + alertCardAvailableCount + "次。", "examHelpOperating");
                    } else {
                        //单选
                        showConfirmCancelAskDialog("你将消耗10积分，排除一个错误答案，本次考试您还可以使用" + alertCardAvailableCount + "次。", "examHelpOperating");
                    }
                } else {
                    alertMessage("当前题已经用过提示卡");
                }
            }

        }
    }

    /**
     * 提示操作
     */
    public void examHelpOperating() {
        showOperatingProgressDialog("获取数据");
        JSONObject questionJsonObject = TypeUtils.getJsonObject(questionJsonArray, currPosition);
        int questionId = TypeUtils.getJsonInteger(questionJsonObject, "id");
        examHelpService.getPropsCard(paperId, itemId, questionId);
//        propsCardSuccess(null);
    }

    /**
     * 加时卡点击
     */
    public void examOvertimeCardClick() {
        /**
         * 延时卡(1)
         */
        this.itemId = 1;
        if (overtimeCardCount <= 0) {
            alertMessage("一堂考试只能用3次延时卡");
        } else {
            showConfirmCancelAskDialog("你将消耗10积分，获得60秒的加时，本次考试您还可以使用" + overtimeCardCount + "次。", "examHelpOperating");
        }
    }

    @UiThread
    @Override
    public void propsCardSuccess(JSONObject jsonObject) {
        cancelOperatingProgressDialog();
        JSONObject dataJsonObject = TypeUtils.getJsonObject(jsonObject, "data");
        if (itemId == 1) {
            long durationTime = TypeUtils.getJsonInteger(dataJsonObject, "duration", 0) * 1000;
            endTime = startTime + durationTime;
            paperJsonObject.put("duration", durationTime);
            overtimeCardCount--;
            paperJsonObject.put("overtimeCardCount", overtimeCardCount);
            alertMessage("加时卡使用成功");
//                    + (TypeUtils.getJsonInteger(paperJsonObject, "duration", 0) * 1000);
        } else {
            JSONObject questionJsonObject = TypeUtils.getJsonObject(questionJsonArray, currPosition);
            boolean multiple = TypeUtils.getJsonBoolean(questionJsonObject, "multiple", true);
            JSONArray optionsCard = null;
            if (multiple) {
                optionsCard = TypeUtils.getJsonArray(dataJsonObject, "correctOptions");
            } else {
                optionsCard = TypeUtils.getJsonArray(dataJsonObject, "incorrectOptions");
            }
//            optionsCard = new JSONArray();
//            optionsCard.add("A");
            questionJsonObject.put("optionsCard", optionsCard);
            alertCardAvailableCount--;
            paperJsonObject.put("alertCardAvailableCount", alertCardAvailableCount);
            ItemQuestionFragment currFragment = paperQuestionListAdapter.getCurrentFragment();

            if (currFragment != null) {
                currFragment.updateData();
            }
            alertMessage("提示卡使用成功");
        }
    }

    @UiThread
    @Override
    public void propsCardError(String error) {
        cancelOperatingProgressDialog();
        alertMessage(error);
    }

    /**
     * 开始计时
     */
    @Background
    public void startTiming() {
        try {
            Thread.sleep(1000);
            updateTimingUI();
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }

    /**
     * 更新ui
     */
    @UiThread
    public void updateTimingUI() {
        long currentTimeMillis = System.currentTimeMillis();
        if (currentTimeMillis >= endTime) {
            examTimeTextView.setText("00:00");
            // alertMessage("交卷");
            examCarryOutAnAssignment();
        } else {
            long intervalDateSecond = (endTime - currentTimeMillis) / 1000;
            long intervalMinute = (intervalDateSecond / 60);
            long intervalSecond = intervalDateSecond % 60;
            examTimeTextView.setText((intervalMinute < 10 ? "0" : "")
                    + intervalMinute + ":" + (intervalSecond < 10 ? "0" : "")
                    + intervalSecond);
            startTiming();
        }
    }

    @UiThread
    @Override
    public void responseError(String error) {
        cancelLoadDataProgressDialog();
        alertMessage(error);
    }

    @UiThread
    @Override
    public void submitAnswersSuccess(JSONObject jsonObject) {
        isCarryOutAnAssignment = true;

        cancelOperatingProgressDialog();
//        JSONObject resultJsonObject = TypeUtils.getJsonObject(jsonObject,
//                "result");
//        int correct = TypeUtils.getJsonInteger(resultJsonObject, "correct", 0);
//        int incorrect = TypeUtils.getJsonInteger(resultJsonObject, "incorrect",
//                0);
//        int award = TypeUtils.getJsonInteger(resultJsonObject, "award", 0);
//        alertMessage("提交成功。奖励：" + award + ";正确=" + correct + ";不正确="
//                + incorrect);
        showCarryOutAnAssignmentAskDialog(jsonObject);
        deleteCurrPaper();

    }

    public void showCarryOutAnAssignmentAskDialog(JSONObject jsonObject) {

        JSONObject resultJsonObject = TypeUtils.getJsonObject(jsonObject,
                "result");
        int correct = TypeUtils.getJsonInteger(resultJsonObject, "correct", 0);
        int incorrect = TypeUtils.getJsonInteger(resultJsonObject, "incorrect",
                0);
        int award = TypeUtils.getJsonInteger(resultJsonObject, "award", 0);
//        alertMessage("提交成功。奖励：" + award + ";正确=" + correct + ";不正确="
//                + incorrect);
        int score = TypeUtils.getJsonInteger(resultJsonObject, "score",
                0);

        int unanswered = TypeUtils.getJsonInteger(resultJsonObject, "unanswered", 0);

        int experience = TypeUtils.getJsonInteger(resultJsonObject, "experience", 0);

//        本次考试
//                得分___分
//        用时___分钟
//                答对____题
//        答错____题
//                未答____题
//        获得积分___
//                获得经验值___
//        感谢您的参与！
//
//        确定
//        :
//        如果是进阶闯关和大师之路，判断一下”没有通过，加油！“和”恭喜您，通过了！“
//        我:
//        额额
//        :
//        随堂检测和限时挑战不用写这2句
        StringBuffer carryOutAnAssignmentAskValue = new StringBuffer();
        carryOutAnAssignmentAskValue.append("得分" + score + "分");
        carryOutAnAssignmentAskValue.append("\n");
        carryOutAnAssignmentAskValue.append("用时" + DateUtils.getHourAndMinuteAndSecond(startTime, carryOutAnAssignmentTime));
        carryOutAnAssignmentAskValue.append("\n");
        carryOutAnAssignmentAskValue.append("答对" + correct + "题");
        carryOutAnAssignmentAskValue.append("\n");
        carryOutAnAssignmentAskValue.append("答错" + incorrect + "题");
        carryOutAnAssignmentAskValue.append("\n");
        carryOutAnAssignmentAskValue.append("未答" + unanswered + "题");
        carryOutAnAssignmentAskValue.append("\n");
        carryOutAnAssignmentAskValue.append("获得积分" + award);
        carryOutAnAssignmentAskValue.append("\n");
        carryOutAnAssignmentAskValue.append("获得经验值" + experience);
        // 6+1 形象大师 7
        // 6+2 维保大师 8
        // 6+3 服务大师 9
        // 6+4 销售大师 10
        // 6+5 商品大师 11
        // 6+6 品牌大师 12
        //6 进价闯关
        if (examTypeInt >= 6 && examTypeInt <= 12) {
            boolean passed = TypeUtils.getJsonBoolean(resultJsonObject, "passed", false);
            carryOutAnAssignmentAskValue.append("\n");
            if (passed) {
                carryOutAnAssignmentAskValue.append("恭喜您，通过了！");
            } else {
                carryOutAnAssignmentAskValue.append("没有通过，加油！");
            }
        }
        carryOutAnAssignmentAskValue.append("\n");
        carryOutAnAssignmentAskValue.append("\n");
        carryOutAnAssignmentAskValue.append("感谢您的参与！");
        if (carryOutAnAssignmentAskDialog == null) {
            carryOutAnAssignmentAskDialog = new CarryOutAnAssignmentAskDialog(this);
        }

        carryOutAnAssignmentAskDialog.show();
        carryOutAnAssignmentAskDialog.setContentValue(carryOutAnAssignmentAskValue.toString());
    }

    public void carryOutAnAssignmentAskDialogDetermine() {
        setResult(Constants.ONLINE_EXAM_CARRY_OUT_AN_ASSIGNMENT_REQUEST_CODE);
        finish();
    }

    @UiThread
    @Override
    public void submitAnswersError(String error) {
        isCarryOutAnAssignment = true;
        cancelOperatingProgressDialog();
        alertMessage(error);
        deleteCurrPaper();
        finish();
    }

    @Override
    public void loadSaiKuangInfoSuccess(JSONObject jsonObject) {

    }

    @Override
    public void loadSaiKuangInfoError(String error) {

    }

    @Override
    public void onPageScrollStateChanged(int arg0) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onPageScrolled(int arg0, float arg1, int arg2) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onPageSelected(int position) {
        int totalCount = TypeUtils.getJsonArraySize(questionJsonArray);
        // if (position >= totalCount) {
        // this.currPosition = position % totalCount;
        // } else {
        this.currPosition = position;
        // }
        // questionNumberListDialogRefreshData();
        examQuestionCountTextView.setText(((currPosition % totalCount) + 1)
                + "/" + totalCount);
    }

    @Override
    public int getCount() {
        return TypeUtils.getJsonArraySize(questionJsonArray);
    }

    @Override
    public void itemClick(int position) {
        // if(position==0)
        // {
        //
        // }else if()
        //
        int totalCount = TypeUtils.getJsonArraySize(questionJsonArray);
        if (this.currPosition % totalCount == position)
            return;
        this.currPosition -= (this.currPosition % totalCount - position);

        viewPager.setCurrentItem(this.currPosition);
        questionNumberListDialogRefreshData();
    }

    @Override
    public void loadItemData(int position,
                             QuestionNumberItemView questionNumberItemView) {
        int totalCount = TypeUtils.getJsonArraySize(questionJsonArray);
        questionNumberItemView.loadData(position,
                TypeUtils.getJsonObject(questionJsonArray, position),
                currPosition % totalCount == position);
    }

    /**
     * 删除当前试卷
     */
    public void deleteCurrPaper() {
        try {
            if (localAnswersContent != null) {
                paperAnswerCacheDao.delete(paperId);
            }
        } catch (Exception e) {
            ErrorUtils.outErrorLog(e);
        }
    }


    @Override
    protected void onDestroy() {
        if (questionNumberListDialog != null) {
            questionNumberListDialog.cancel();
        }
        if (!isCarryOutAnAssignment) {
            try {
                // 极限考试不保存状态   闯关保存状态 && !"6".equals(examType)
                if (!"5".equals(examType)) {
                    if (paperAnswerCacheDao != null && paperJsonObject != null) {
                        int intExamType = 0;
                        try {
                            intExamType = Integer.parseInt(examType);
                        } catch (Exception ex) {
                            intExamType = 0;
                        }
                        paperAnswerCacheDao.save(paperId,
                                paperJsonObject.toString(), endTime, intExamType);
                    }
                }
            } catch (Exception e) {
                ErrorUtils.outErrorLog(e);
            }
        }

        try {
            if (paperAnswerCacheDao != null) {
                paperAnswerCacheDao.delete();
            }
        } catch (Exception e) {
            ErrorUtils.outErrorLog(e);
        }

        super.onDestroy();
    }

}
